<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Base  extends Model
{
    public function scopeAndFilterWhere($query, ...$parameters)
    {
        $value = $this->getValue(...$parameters);
        if ($value || ($value == 0 && $value != '')) {
            return $query->where(...$parameters);
        }
        return $query;
    }


    public function scopeOrFilterWhere($query, ...$parameters)
    {
        $value = $this->getValue(...$parameters);
        if ($value || ($value == 0 && $value != '')) {
            return $query->orWhere(...$parameters);
        }
        return $query;
    }

    public function scopeMultiSearch($query, array $columns)
    {
        $query = collect($columns)->map(function ($column) use ($query) {
            $value = request($column);
            if ($value) {
                $query->where($column, $value);
            }
        });
        return $query;
    }

    public function scopeAndFilterBetweenWhere($query, $column, $start_time, $end_time)
    {
        if ($start_time) {
            $start_time = date('Y-m-d 00:00:00', strtotime($start_time));
            $query->where($column, '>=', $start_time);
        }
        if ($end_time) {
            $end_time = date('Y-m-d 23:59:59', strtotime($end_time));
            $query->where($column, '<=', $end_time);
        }
        return $query;
    }

    private function getValue(...$parameters)
    {
        if (count($parameters) == 3) {
            return $parameters[2];
        }
        return $parameters[1] ?? '';
    }

    /*
     * 数组条件查询（值包含数字0）
     *
     */
    public function scopeMultiWhere($query, $arrColumn)
    {
        if (!empty($arrColumn) && is_array($arrColumn)) {
            foreach ($arrColumn as $key => $value) {
                if ($value || $value === 0) {
                    if (is_array($value)) {
                        $args = [$key, $value[0], $value[1]];
                        call_user_func_array([$query, 'where'], $args);
                    } else {
                        $args = [$key, $value];
                        call_user_func_array([$query, 'where'], $args);
                    }
                }
            }
        }
        return $query;
    }

}
